//
// Source code recreated from a .class file by IntelliJ IDEA
// (powered by Fernflower decompiler)
//

package com.ruoyi.live.exam.service;

import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.ruoyi.live.base.domain.LiveExam;
import com.ruoyi.live.base.domain.LiveExamJudge;
import com.ruoyi.live.base.domain.LiveExamUser;
import com.ruoyi.live.base.domain.User;
import com.ruoyi.live.base.mapper.*;
import com.ruoyi.live.base.service.ILiveExamJudgeService;
import com.ruoyi.live.tool.commons.ICommons;
import com.ruoyi.live.tool.commons.IConvert;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

@Service
public class LiveExamJudgeService {
    private static final Logger log = LoggerFactory.getLogger(LiveExamJudgeService.class);
    @Autowired
    LiveExamJudgeMapper dao;
    @Autowired
    ILiveExamJudgeService examJudgeService;
    @Autowired
    LiveExamExpertMapper examExpertDao;
    @Autowired
    LiveExamMapper examDao;
    @Autowired
    UserMapper userDao;
    @Autowired
    JdbcTemplate jdbcTemplate;
    @Autowired
    LiveExamUserMapper examUserDao;

    public LiveExamJudgeService() {
    }

    public void addLiveExamJudge(LiveExamJudge entity) throws Exception {
        try {
            this.dao.insert(entity);
        } catch (Exception var3) {
            var3.printStackTrace();
            log.error("新增LiveExamJudge失败,编号LiveExamJudgeService-addLiveExamJudge-1");
            throw new Exception("新增失败,编号LiveExamJudgeService-addLiveExamJudge-1");
        }
    }

    public void updateLiveExamJudge(LiveExamJudge entity) throws Exception {
        try {
            this.dao.updateById(entity);
        } catch (Exception var3) {
            var3.printStackTrace();
            log.error("更新LiveExamJudge失败,编号LiveExamJudgeService-updateLiveExamJudge-1,id:{}", entity.getId());
            throw new Exception("更新失败,编号LiveExamJudgeService-updateLiveExamJudge-1");
        }
    }

    public LiveExamJudge getLiveExamJudge(Long id) {
        return (LiveExamJudge)this.dao.selectById(id);
    }

    public int deleteLiveExamJudge(String[] ids) throws Exception {
        if (ids.length == 0) {
            throw new Exception("请选择要删除的数据,编号LiveExamJudgeService-deleteLiveExamJudge-1");
        } else {
            try {
                int count = 0;

                for(int i = 0; i < ids.length; ++i) {
                    if (!ICommons.isNullOrEmpty(ids[i])) {
                        count += this.dao.deleteById(IConvert.string2long(ids[i]));
                    }
                }

                return count;
            } catch (Exception var4) {
                var4.printStackTrace();
                log.error("删除LiveExamJudge失败,编号LiveExamJudgeService-deleteLiveExamJudge-2,ids:{}", ids.toString());
                throw new Exception("删除的数据失败,编号LiveExamJudgeService-deleteLiveExamJudge-2");
            }
        }
    }

    public List<LiveExamJudge> query(LiveExamJudge entity) {
        QueryWrapper<LiveExamJudge> wrapper = (QueryWrapper)((QueryWrapper)((QueryWrapper)((QueryWrapper)((QueryWrapper)((QueryWrapper)(new QueryWrapper()).eq(!ICommons.isNullOrEmpty(entity.getId()), "id", entity.getId())).eq(!ICommons.isNullOrEmpty(entity.getExamId()), "exam_id", entity.getExamId())).eq(!ICommons.isNullOrEmpty(entity.getExamUserId()), "exam_user_id", entity.getExamUserId())).eq(!ICommons.isNullOrEmpty(entity.getUserJudgeId()), "user_judge_id", entity.getUserJudgeId())).eq(!ICommons.isNullOrEmpty(entity.getUserPlayerId()), "user_player_id", entity.getUserPlayerId())).eq(!ICommons.isNullOrEmpty(entity.getGroupNo()), "group_no", entity.getGroupNo());
        return this.dao.selectList(wrapper);
    }

    public LiveExam getExam() {
        return (LiveExam)this.examDao.selectList((Wrapper)null).get(0);
    }

    public List<User> getExperts() {
        return this.userDao.selectList(new QueryWrapper((new User()).setUserState(1).setUserType(4)));
    }

    public Integer queryUserCount(Long id) {
        String sql = "select count(1) from user where user_type = 3 and user_state = 1 and class_id in (select a.class_id from live_exam_class a where exam_id = ? )";
        return (Integer)this.jdbcTemplate.queryForObject(sql, Integer.class, new Object[]{id});
    }

    public void doCreateExpert(Long examId, Integer userGroupCount, Integer userPc, Integer judgePc) throws Exception {
        String sql = "select id,user_login_name from user where user_type = 4 and user_state = 1 and user_duty = ?";
        List<User> experts = this.jdbcTemplate.query(sql, new Object[]{judgePc}, new BeanPropertyRowMapper(User.class));
        if (experts.size() == 0) {
            throw new Exception("专家人数不足");
        } else {
            List<Long> expertIds = (List)experts.stream().map((exp) -> {
                return exp.getId();
            }).collect(Collectors.toList());
            sql = "select id,user_login_name from user where class_id in (select b.class_id from live_exam_class b where b.exam_id = ?) and user_state = 1 and user_type = 3 and user_duty = ?";
            List<User> users = this.jdbcTemplate.query(sql, new Object[]{examId, userPc}, new BeanPropertyRowMapper(User.class));
            List<Long> userIds = (List)experts.stream().map((us) -> {
                return us.getId();
            }).collect(Collectors.toList());
            if (users.size() == 0) {
                throw new Exception("选手人数不足");
            } else {
                String sqlCount = "select ifnull(count(1),0) count from live_exam_expert a where a.judge_id in (select b.id from live_exam_judge b where b.exam_id = ? and b.user_judge_id in (" + StringUtils.join(userIds, ",") + ") and b.user_player_id in (" + StringUtils.join(userIds, ",") + "))";
                List<Map<String, Object>> jugs = this.jdbcTemplate.queryForList(sqlCount, new Object[]{examId});
                if (jugs.size() > 0) {
                    Integer count = IConvert.object2int(((Map)jugs.get(0)).get("count"));
                    if (count > 0) {
                        throw new Exception("已开始评审，裁判分配被拒绝");
                    }
                }

                String deleteSql = "delete b.* from live_exam_judge b where b.exam_id = ? and b.user_judge_id in (" + StringUtils.join(userIds, ",") + ") and b.user_player_id in (" + StringUtils.join(userIds, ",") + ")";
                this.jdbcTemplate.update(deleteSql, new Object[]{examId});
                Integer expertCount = experts.size();
                List<LiveExamUser> eus = this.examUserDao.selectList((new QueryWrapper((new LiveExamUser()).setExamId(examId))).select(new String[]{"id", "create_user"}));
                Map<Long, Long> res = (Map)eus.stream().collect(Collectors.toMap(LiveExamUser::getCreateUser, (eu) -> {
                    return eu.getId();
                }));
                Integer groupCount = expertCount / userGroupCount + (expertCount % userGroupCount == 0 ? 0 : 1);
                Map<Integer, List<User>> groups = new HashMap();

                for(int i = 1; i <= groupCount; ++i) {
                    List<User> exps = new ArrayList();

                    for(int j = (i - 1) * userGroupCount; j < (i - 1) * userGroupCount + userGroupCount && j < experts.size(); ++j) {
                        exps.add(experts.get(j));
                    }

                    groups.put(i, exps);
                }

                Integer baseNo = 1;
                String maxSql = "select max(group_no) gno from live_exam_judge";
                List<Map<String, Object>> maxRes = this.jdbcTemplate.queryForList(maxSql);
                if (maxRes.size() > 0) {
                    baseNo = IConvert.object2int(((Map)maxRes.get(0)).get("gno")) + 1;
                }

                for(int i = 0; i < users.size(); ++i) {
                    User user = (User)users.get(i);

                    for(int j = 0; j < ((List)groups.get(i % groupCount + 1)).size(); ++j) {
                        User expert = (User)((List)groups.get(i % groupCount + 1)).get(j);
                        this.dao.insert((new LiveExamJudge()).setExamId(examId).setExamUserId((Long)res.get(user.getId())).setUserPlayerId(user.getId()).setUserPlayerName(user.getUserLoginName()).setGroupNo(i % groupCount + baseNo).setUserJudgeId(expert.getId()).setUserJudgeName(expert.getUserLoginName()));
                    }
                }

            }
        }
    }

    public List<Map<String, Object>> getGroups(Long id) {
        String sql = "select GROUP_CONCAT(DISTINCT(user_judge_name)) judge,GROUP_CONCAT(DISTINCT(user_player_name)) player,group_no no from live_exam_judge where exam_id = " + id + " group by group_no";
        List<Map<String, Object>> list = this.jdbcTemplate.queryForList(sql);
        Iterator var4 = list.iterator();

        while(var4.hasNext()) {
            Map<String, Object> res = (Map)var4.next();
            res.put("judges", res.get("judge").toString().split(","));
            res.put("players", res.get("player").toString().split(","));
        }

        return list;
    }

    public void doSaveJudge(LiveExamUser examUser) {
        Long count = this.dao.selectCount(new QueryWrapper((new LiveExamJudge()).setExamUserId(examUser.getId())));
        if (count > 0l) {
            List<LiveExamJudge> juds = this.dao.selectList(new QueryWrapper((new LiveExamJudge()).setExamUserId(examUser.getId())));
            Iterator var4 = juds.iterator();

            while(var4.hasNext()) {
                LiveExamJudge judge = (LiveExamJudge)var4.next();
                if (0 == judge.getState()) {
                    this.dao.updateById((new LiveExamJudge()).setId(judge.getId()).setState(1));
                }
            }
        } else {
            User createUser = (User)this.userDao.selectById(examUser.getCreateUser());
            List<User> experts = this.userDao.selectList((new QueryWrapper((new User()).setUserSchool(createUser.getClassId()))).select(new String[]{"id", "user_login_name"}));
            List<LiveExamJudge> judges = new ArrayList();
            Iterator var6 = experts.iterator();

            while(var6.hasNext()) {
                User user = (User)var6.next();
                judges.add((new LiveExamJudge()).setExamId(examUser.getExamId()).setExamUserId(examUser.getId()).setUserJudgeId(user.getId()).setUserPlayerId(createUser.getId()).setGroupNo(1).setUserJudgeName(user.getUserLoginName()).setUserPlayerName(createUser.getUserLoginName()).setState(1));
            }

            this.examJudgeService.saveBatch(judges);
        }

    }

    public void doCsh() throws Exception {
        Long count = this.examExpertDao.selectCount((Wrapper)null);
        if (count > 0l) {
            throw new Exception("");
        } else {
            this.dao.delete((Wrapper)null);
        }
    }
}
